<?php

namespace app\admin\controller;

use app\admin\model\Showpinkunmember;
use app\admin\model\Villnavigation;
use app\admin\model\Villnavigationdetail;

use think\Db;
use think\Exception;
use think\Request;

class Townconfig extends Base
{

    public function _initialize(){
        parent::_initialize();
    }

    public function config(Request $request){
        $townId = session('ADMIN')['townId'];
        $config = '';
        $Townconfig = \app\admin\model\Townconfig::where('townId',$townId)->find();
        if($Townconfig){
            $config = $Townconfig;
        }

        $nav = null;
        // 镇导航详情
        $Villnavigationdetail = Villnavigationdetail::where('townId', $townId)->select();
        if($Villnavigationdetail){
            $nav = $Villnavigationdetail;
        }

        $area = getAreaNameByTownId($townId);
        $area['villageName'] = '0';
        // 默认导航按钮
        $Villnavigation = Villnavigation::where(true)->select();

        $this->assign('config', $config);
        $this->assign('nav', $nav);
        $this->assign('townId', $townId);
        $this->assign('serarea', $area);
        $this->assign('navigation', $Villnavigation);

        return $this->fetch();
    }

    public function addjoinmember(Request $request){
        if ($request->isAjax()) {
            $params = $request->param();
            if(!$params['townId']){
                return json(['code' => 0, 'msg' => '添加失败！']);
            }

            //$ids = $params['id'];
            $ids = explode(',', $params['ids']);
            $data = [];
            $listadd = [];
            $result = false;
            foreach ($ids as $key => $id) {
                $data['townId'] = $params['townId'];
                $data['memberId'] = $id;
                // 是否已添加
                $isshowdata = Showpinkunmember::where($data)->find();
                if($isshowdata){
                    continue;
                }
                array_push($listadd,$data);
            }
            if(!empty($listadd)){
                $Showpinkunmember = new Showpinkunmember();
                $result = $Showpinkunmember->saveAll($listadd);
            }

            if($result !== false) {
                return json(['code' => 1, 'msg' => '添加成功！']);
            } else {
                return json(['code' => 0, 'msg' => '添加失败']);
            }
        } else {
            return json(['code' => 0, 'msg' => '请求方式不正确！']);
        }
    }

    /**
     * 成员列表
     * @return \think\response\Json
     */
    public function memberlist(){
        $request = $this->request;
        $param = $request->param();
        $model = model('Member');

        // 每页起始条数
        $start = $param['start'];
        // 每页显示条数
        $length = $param['length'];

        $where = [
            'isParty' => 1,
            'organizationId' => [['neq', 0], ['neq', ''], ['neq', 'null'], 'and']
        ];
        if($param['townId']){
            $where['townId'] = $param['townId'];
        }
        if($param['search']['value']) {
            $filter = json_decode($param['search']['value'],true);
            if(isset($filter['cityId']) && $filter['cityId']){
                $where['cityId'] = $filter['cityId'];
            }
            if(isset($filter['xianId']) && $filter['xianId']){
                $where['xianId'] = $filter['xianId'];
            }
            if(isset($filter['townId']) && $filter['townId']){
                $where['townId'] = $filter['townId'];
            }
            if(isset($filter['villageId']) && $filter['villageId']){
                $where['villageId'] = $filter['villageId'];
            }
            if(isset($filter['name']) && $filter['name']){
                $where['name'] = ['like', '%'.$filter['name'].'%'];
            }
        }

        $list = $model->alias('a')->where($where)->limit($start, $length)->select();
        $count = $model->alias('a')->where($where)->count();

        $result = [
            'status' => '1',
            'draw' => $param['draw'],
            'data' => $list,
            'recordsFiltered' => $count,
            'recordsTotal' => $count,
        ];

        return json($result);
    }

    /**
     * 有权限人员列表
     * @return \think\response\Json
     */
    public function joinmeetingList(Request $request){
        $townId = session('ADMIN')['townId'];

        $param = $request->param();
        $model = model('Townconfig');

        // 每页起始条数
        $start = $param['start'];
        // 每页显示条数
        $length = $param['length'];

        if(empty($param['id'])){
            $result = [
                'status' => '0',
                'draw' => $param['draw'],
                'data' => [],
                'recordsFiltered' => 0,
                'recordsTotal' => 0,
            ];
            return json($result);
        }
        $where = [
            'a.townId' => $townId,
            's.status' => 1
        ];

        $join = [
            ['__SHOWPINKUNMEMBER__ s','s.townId=a.townId'],
            ['__MEMBER__ m', 's.memberId = m.id'],
        ];
        $field = 'a.*, m.avatar, m.name, m.job,s.id as sid,s.memberId';
        $list = $model->alias('a')->where($where)->join($join)->field($field)->limit($start, $length)->select();
        $count = $model->alias('a')->where($where)->join($join)->count();

        $result = [
            'status' => '1',
            'draw' => $param['draw'],
            'data' => $list,
            'recordsFiltered' => $count,
            'recordsTotal' => $count,
        ];
        return json($result);
    }

    public function configPost(Request $request){
        if($request->isPost()){
            $param = $request->param();
            Db::startTrans();
            try{
                $Townconfig = \app\admin\model\Townconfig::where('townId',$param['townId'])->find();
                $Villnavigation = Db::table('villnavigation')->select();
                $Villnavigationdetail = Db::table('villnavigationdetail')->where('townId',$param['townId'])->select();
                $imglist = $this->getNavimg($Villnavigationdetail,$param,$Villnavigation);

                if($Townconfig){
                    //更新
                    $Townconfig->dongtaioff = $param['dongtaioff'];
                    $Townconfig->pinglunoff = $param['pinglunoff'];
                    $Townconfig->dongtaicheckoff = $param['dongtaicheckoff'];
                    $Townconfig->isshowpinkun = $param['isshowpinkun'];
                    if($Townconfig->issetnavigation == 0){
                        $Townconfig->issetnavigation = 1;
                    }
                    $Townconfig->save();

                    $this->insertNavigation($param, $imglist, $Villnavigation, $Villnavigationdetail);
                }else{
                    $Townconfig = new \app\admin\model\Townconfig();
                    //增加
                    $Townconfig->townId = $param['townId'];
                    $Townconfig->dongtaioff = $param['dongtaioff'];
                    $Townconfig->pinglunoff = $param['pinglunoff'];
                    $Townconfig->dongtaicheckoff = $param['dongtaicheckoff'];
                    $Townconfig->isshowpinkun = $param['isshowpinkun'];
                    $Townconfig->issetnavigation = 1;
                    $Townconfig->save();

                    $this->insertNavigation($param, $imglist, $Villnavigation, $Villnavigationdetail);
                }

                Db::commit();
                return $this->success('修改成功！', 'admin/' . strtolower($this->model) . '/config');
            }catch (Exception $ex){
                Db::rollback();
                return $this->error('修改失败！', 'admin/' . strtolower($this->model) . '/config');
            }
        }
    }

    private function insertNavigation($param, $imglist, $Villnavigation, $Villnavigationdetail){
        if(isset($param['villnavigation'])){
            if(!is_array($param['villnavigation'])){
                $idarr = explode(' ', $param['villnavigation']);
            }else{
                $idarr = $param['villnavigation'];
            }
        }
        if(!$Villnavigationdetail){
            $insertlist = [];
            if(!isset($idarr)){
                foreach ($Villnavigation as $v){
                    array_push($insertlist,['typeId'=>$v['id'],'name'=>$v['name'],'townId'=>$param['townId'],'imgurl'=>$imglist[$v['id']],'status'=>2]);
                }
            }else{
                foreach ($Villnavigation as $v){
                    if(in_array($v['id'],$idarr)){
                        array_push($insertlist,['typeId'=>$v['id'],'name'=>$v['name'],'townId'=>$param['townId'],'imgurl'=>$imglist[$v['id']],'status'=>1]);
                    }else{
                        array_push($insertlist,['typeId'=>$v['id'],'name'=>$v['name'],'townId'=>$param['townId'],'imgurl'=>$imglist[$v['id']],'status'=>2]);
                    }
                }
            }

            $model = new Villnavigationdetail();
            $model->saveAll($insertlist);
        }else{
            $model = new Villnavigationdetail();
            foreach ($Villnavigationdetail as $value){
                if(isset($idarr)){
                    if(in_array($value['typeId'],$idarr)){
                        $model->where('id',$value['id'])->update(['status'=>1,'imgurl'=>$imglist[$value['typeId']]]);
                    }else{
                        $model->where('id',$value['id'])->update(['status'=>2,'imgurl'=>$imglist[$value['typeId']]]);
                    }
                }else{
                    $model->where('id',$value['id'])->update(['status'=>2,'imgurl'=>$imglist[$value['typeId']]]);
                }
            }
        }
    }

    private function getNavimg($Villnavigationdetail, $param, $Villnavigation){
        $imglist = [];
        if(!$Villnavigationdetail){
            if($param['imgurl1']){
                $imglist['1'] = $param['imgurl1'];
            }else{
                $imglist['1'] = $Villnavigation[0]['imgurl'];
            }
            if($param['imgurl2']){
                $imglist['2'] = $param['imgurl2'];
            }else{
                $imglist['2'] = $Villnavigation[1]['imgurl'];
            }
            if($param['imgurl3']){
                $imglist['3'] = $param['imgurl3'];
            }else{
                $imglist['3'] = $Villnavigation[2]['imgurl'];
            }
            if($param['imgurl4']){
                $imglist['4'] = $param['imgurl4'];
            }else{
                $imglist['4'] = $Villnavigation[3]['imgurl'];
            }
            if($param['imgurl5']){
                $imglist['5'] = $param['imgurl5'];
            }else{
                $imglist['5'] = $Villnavigation[4]['imgurl'];
            }
        }else{
            if($param['imgurl1']){
                $imglist['1'] = $param['imgurl1'];
            }else{
                $imglist['1'] = $this->setDtailimg($Villnavigationdetail,1);
            }
            if($param['imgurl2']){
                $imglist['2'] = $param['imgurl2'];
            }else{
                $imglist['2'] = $this->setDtailimg($Villnavigationdetail,2);
            }
            if($param['imgurl3']){
                $imglist['3'] = $param['imgurl3'];
            }else{
                $imglist['3'] = $this->setDtailimg($Villnavigationdetail,3);
            }
            if($param['imgurl4']){
                $imglist['4'] = $param['imgurl4'];
            }else{
                $imglist['4'] = $this->setDtailimg($Villnavigationdetail,4);
            }
            if($param['imgurl5']){
                $imglist['5'] = $param['imgurl5'];
            }else{
                $imglist['5'] = $this->setDtailimg($Villnavigationdetail,5);
            }
        }

        return $imglist;
    }

    private function setDtailimg($data, $typeId){
        $imgurl = '';
        foreach ($data as $val){
            if($val['typeId'] == $typeId){
                $imgurl = $val['imgurl'];
            }
        }

        return $imgurl;
    }

    public function delmember(Request $request){
        $param = $request->param();
        $result = false;
        $Showpinkunmember = Showpinkunmember::get($param['id']);
        if($Showpinkunmember){
            $Showpinkunmember->status = 2;
            $result = $Showpinkunmember->save();
        }

        if($result !== false){
            return json(['code' => 1, 'msg' => '删除成功！']);
        }else{
            return json(['code' => 0, 'msg' => '删除失败']);
        }
    }
}